<?php


namespace App\Http\Controllers\Admin;



use App\Common\CheckMenu;
use App\Http\Controllers\Controller;
use App\Http\Response\JsonResult;
use App\Http\Response\ResponseCode;
use App\Models\System\SystemRoleModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

class BaseController extends Controller
{
    protected $queryService   = '';     //查询service
    protected $commandService = '';     //增/更/删 service
    protected $model = '';
    protected $validate = '';           //校验器
    protected $viewAuthRoute = [];      //页面权限，以 名称对路由为数组，如 [ 'add'=>'/system/role/add','update'=>'/system/role/add' ]

    //首页的一个模板，可用在子类下直接调用该方法返回比较简单的列表页面.
    protected function lists_index()
    {
        $request = \request();
        if ( $request->ajax() ) {
            if (empty($this->model)) {
                return JsonResult::returnJson(ResponseCode::MODEL_NO_DEFINE);
            }

            if (!empty($this->queryService)) {
                $queryService = app($this->queryService);

                if ( method_exists($queryService,'index') ) {

                    return JsonResult::returnJson(ResponseCode::SUCCESS,$queryService->index());
                }
            }

            $queryModel = app($this->model);

            $page = $request->input('page',1);
            $limit = $request->input('limit',30);

            $offset = ($page-1)*$limit ;

            $lists = $queryModel->offset($offset)
                                ->limit($limit)
                                ->get();
            $total = $queryModel->count();

            return JsonResult::returnJson(ResponseCode::SUCCESS,['lists'=>$lists,'count'=>$total]);
        }

        $viewArrName = $this->getViesFormName();

        $viewName = 'admin.'.$viewArrName['module'].'.'.$viewArrName['controller'].'.index';
        $viewAuthBool = $this->checkViewAuth($this->viewAuthRoute);

        return view($viewName,['viewAuthBool'=>$viewAuthBool]);
    }


    public function add(Request $request)
    {
        if ($request->ajax()) {

            //先校验
            if ( !empty($this->validate) ) {
                $validate = app($this->validate);
                if ( isset($validate->addRule ) ){
                    $request->validate( $validate->addRule );
                }
            }

            //如果存在$commandService类的add方法，先调用该方法来添加
            if ( !empty($this->commandService) ) {
                $commandService = app($this->commandService);
                if ( method_exists($commandService,'add') ) {
                    return $commandService->add($request->all());
                }
            }

            //用model来添加
            if (empty($this->model)) {
                return JsonResult::returnJson(ResponseCode::MODEL_NO_DEFINE);
            }

            $savedModel = app($this->model);

            try{

                $savedModel->fill($request->all())->save();

                return JsonResult::returnJson(ResponseCode::SUCCESS);

            }catch (\Exception $exception) {

                return JsonResult::returnJson(ResponseCode::EXCEPTION_MESSAGE,[],$exception->getMessage());

            }

        }

        $viewArrName = $this->getViesFormName();

        $viewName = 'admin.'.$viewArrName['module'].'.'.$viewArrName['controller'].'.form';

        return view($viewName);

    }

    public function update(Request $request)
    {
        if (empty($this->model)) {
            return JsonResult::returnJson(ResponseCode::MODEL_NO_DEFINE);
        }
        $this->model = app($this->model);
        $info = $this->model->find($request->input('id'));

        if (empty($info)) {
            abort(404);
        }

        if ($request->ajax()) {

            //先校验
            if ( !empty($this->validate) ) {
                $validate = app($this->validate);
                if ( isset($validate->updateRule ) ){
                    $request->validate( $validate->updateRule );
                }
            }

            //如果存在$commandService类的update方法，先调用该方法来添加
            if ( !empty($this->commandService) ) {
                $commandService = app($this->commandService);
                if ( method_exists($commandService,'update') ) {
                    return $commandService->update($info,$request->all());
                }
            }

            //用model来实现
            foreach ($request->all() as $key => $item) {
                if ( isset($info->$key) ) {
                    $info->$key = $item;
                }
            }

            try{

                $info->save();

                return JsonResult::returnJson(ResponseCode::SUCCESS);

            }catch (\Exception $exception) {

                return JsonResult::returnJson(ResponseCode::EXCEPTION_MESSAGE,[],$exception->getMessage());

            }

        }

        $viewArrName = $this->getViesFormName();

        $viewName = 'admin.'.$viewArrName['module'].'.'.$viewArrName['controller'].'.form';

        return view($viewName,['info'=>$info]);
    }

    /**
     * 获取 模块(相对于admin目录下)和控制器名(没有后面的controller名称) ,并且都是小写
     * @return array
     */
    protected function getViesFormName()
    {
        $routeAction = Route::currentRouteAction() ;
        $routeArray = explode('@',$routeAction);
        $names = explode('\\',$routeArray[0]);
        $module     = $names[count($names)-2];
        $controller = $names[count($names)-1];
        $controller = substr($controller,0,strlen($controller)-10);

        return ['module'=> strtolower($module) ,'controller'=> strtolower($controller) ];
    }

    /**
     * 获取页面权限的 权限数组
     * @param $viewAuthRoute, 页面权限路由，参考最上面定义的$viewAuthRoute
     * @return array,   以名称对布尔值的数组，如 [ 'add'=> true, 'update'=>false ]
     */
    protected function checkViewAuth($viewAuthRoute)
    {
        $viewAuthBool = [];
        $roleIds = session('roleIds');
        foreach ($viewAuthRoute as $key => $item) {

            if (  in_array( SystemRoleModel::SUPER_ADMIN,$roleIds ) ) {
                $viewAuthBool[$key] = true;
            }else {
                if ( CheckMenu::isPass($item) ) {
                    $viewAuthBool[$key] = true;
                } else {
                    $viewAuthBool[$key] = false;
                }
            }

        }

        return $viewAuthBool;
    }


}